package jfdi;

import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint.Style;
import android.graphics.Rect;

import util.Mlog;
import jfdi.event.DragDetector;

public class DragNode extends Label implements DragDetector.DragHandler {

    private DragDetector mDragger;
    private Rect mBounds;
    private int[] mDragOffset;
    private Rect oldBounds;
    private long ts;
    
    public DragNode(NodeHost host) {
        super(host);
    }
    
    @Override
    protected void init() {
        super.init();
        mDragger = new DragDetector(this);
        mHost.addTouchListener(mDragger);
        mBounds = new Rect();
        mDragOffset = new int[2];
        oldBounds = new Rect();
    }
    
    @Override
    public void layout(int l, int t, int r, int b) {
        super.layout(l, t, r, b);
        mBounds.left = mLeft;
        mBounds.top = mTop;
        mBounds.right = mRight;
        mBounds.bottom = mBottom;
    }
    
    @Override
    public void render(Canvas canvas) {
        mPaint.setStyle(Style.FILL);
        mPaint.setColor(Color.LTGRAY);
        canvas.drawRect(0, 0, getWidth(), getHeight(), mPaint);
        super.render(canvas);
//        if (ts > 0) {
//            Mlog.i("drag", "delay : ", System.currentTimeMillis() - ts);
//            ts = 0;
//        }
    }

    // DragHandler

    @Override
    public Rect getBounds() {
        return mBounds;
    }

    @Override
    public void onStartDrag(int x, int y) {
        mDragOffset[0] = x - mLeft;
        mDragOffset[1] = y - mTop;
        oldBounds.left = mLeft;
        oldBounds.top = mTop;
        oldBounds.right = mRight;
        oldBounds.bottom = mBottom;
    }

    public void onDrag(int x, int y) {
        ts = System.currentTimeMillis();
        int l, r, t, b;
        l = x - mDragOffset[0];
        t = y - mDragOffset[1];
        r = l + oldBounds.width();
        b = t + oldBounds.height();
        layout(l, t, r, b);
        mHost.invalidate();
    }

    @Override
    public void onEndDrag(int x, int y) {
        layout(oldBounds.left, oldBounds.top, oldBounds.right, oldBounds.bottom);
        mHost.invalidate();
    }
}
